import WxRequest from "./request"
import { toast, modal } from "./extendAPI";
import { getStorage, clearStorage } from "./storage"
import { env } from "./env"

const http = new WxRequest({
  baseUrl: env.baseUrl
})

http.interceptors.request = (config) => {
  const token = getStorage('token')
  return config
}

http.interceptors.response = async (res) => {
  const { isSuccess, data } = res
  if (!isSuccess) {
    toast({ title: '网络异常请重试', icon: 'error' })
    return Promise.reject(res)
  }
  // 判断返回的状态码
  switch (data.code) {
    case 200:
      return data
    case 208:
      const res = await modal({ content: '鉴权失败,请重新登录', showCancel: false })
      if (res) {
        // 清除本地存储的全部信息
        clearStorage()
        wx.navigateTo({ url: '/pages/login/login' })
      }
      return Promise.reject(res)
    default:
      toast({ title: '程序出现异常，请联系客服或稍后重试' })
      return Promise.reject(res)
  }
}

export default http